package com.sdgs.app.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * springcontext工具类。
 * Created by licheng on 2017/11/3.
 */

public final class SpringContextUtil {

    /**
     * 私有构造方法，防止此类被初始化。
     */
    private SpringContextUtil() { }

    /**
     */
    private static ApplicationContext context;

    /**
     * @param applicationContext applicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    /**
     * 根据beanName获取相应的bean。
     * @param beanName  beanName
     * @param <T>       bean Type
     * @return bean
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        return (T) getContext().getBean(beanName);
    }

    /**
     * 根据beanName获取相应的bean。
     * @param requiredType  requiredType
     * @param <T>       bean Type
     * @return bean
     */
    public static <T> T getBean(Class<T> requiredType) {
        return (T) getContext().getBean(requiredType);
    }

    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 获取当前HttpServletRequest。
     * @author licheng
     * @return HttpServletRequest
     * @throws IllegalStateException
     * @since V1.0.0
     */
    public static HttpServletRequest getCurrentRequest() throws IllegalStateException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes == null) {
            throw new IllegalStateException("Current thread does not contain request context.");
        }
        return requestAttributes.getRequest();
    }

    /**
     *
     */
    public static class Setter implements ApplicationContextAware {
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) {
            SpringContextUtil.setApplicationContext(applicationContext);
        }
    }

}